/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.esotericsoftware.minlog.Log;
import com.yami.shop.bean.app.dto.BookDto;
import com.yami.shop.bean.model.Book;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.service.BookService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.util.StringUtils;

import java.util.List;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author lanhai
 */
@RestController
@Slf4j
@RequestMapping("/shop/book")
@Tag(name = "公告管理接口")
@AllArgsConstructor
//手机端控制器
public class BookController {

    private BookService bookService;

    

    /**
     * 置顶公告列表接口
     */
    @GetMapping("/topBookList")
    @Operation(summary = "置顶公告列表信息" , description = "获取所有置顶公告列表信息")
    public ServerResponseEntity<List<BookDto>> getTopBookList() {
        List<Book> bookList = bookService.listBook();
        List<BookDto> bookDtoList = BeanUtil.copyToList(bookList, BookDto.class);
        return ServerResponseEntity.success(bookDtoList);
    }

    /**
     * 获取公告详情
     */
    @GetMapping("/info/{id}")
    @Operation(summary = "公告详情" , description = "获取公告id公告详情")
    public ServerResponseEntity<BookDto> getBookById(@PathVariable("id") Long id) {
        Book book = bookService.getBookById(id);
        // System.out.println(book);
        
        log.info("book内容: {}", book);

        BookDto bookDto = BeanUtil.copyProperties(book, BookDto.class);
        return ServerResponseEntity.success(bookDto);
    }

    /**
     * 公告列表
     */
    @GetMapping("/bookList")
    public ServerResponseEntity<IPage<Book>> getBookPage(
            PageParam<Book> pageParam, 
            Book book,
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false) String keyword) {  // 新增keyword参数

        // 1. 构建查询条件（不执行分页）
        LambdaQueryWrapper<Book> wrapper = new LambdaQueryWrapper<Book>()
            .eq(categoryId != null, Book::getFid, categoryId)
            .eq(book.getStatus() != null, Book::getStatus, book.getStatus())
            .nested(StringUtils.hasText(keyword),  // 优先使用keyword搜索
                nw -> nw.like(Book::getTitle, keyword)
                       // .or()
                       // .like(Book::getContent, keyword)
            )
            // 如果keyword为空，再使用title搜索
            .nested(StringUtils.isEmpty(keyword) && StringUtils.hasText(book.getTitle()),
                nw -> nw.like(Book::getTitle, book.getTitle())
                       // .or()
                       // .like(Book::getContent, book.getTitle())
            )
            .orderByDesc(Book::getUpdateTime);

        // 2. 计算实际总页数
        long total = bookService.count(wrapper);
        int totalPages = (int) Math.ceil((double) total / pageParam.getSize());

        // 3. 校正页码（如果当前页超过总页数，则返回最后一页）
        if (pageParam.getCurrent() > totalPages && totalPages > 0) {
            pageParam.setCurrent(totalPages);
        }

        // 4. 执行分页查询
        IPage<Book> bookPage = bookService.page(pageParam, wrapper);
        return ServerResponseEntity.success(bookPage);
    }
}




